package com.xuzhiguang.lightnat.server.core.server.transfer.processor;

import com.xuzhiguang.lightnat.common.manager.ProxyChannelManager;
import com.xuzhiguang.lightnat.common.message.MessageProcessor;
import com.xuzhiguang.lightnat.common.message.NatMessage;
import com.xuzhiguang.lightnat.common.message.transfer.ConnectRequest;
import com.xuzhiguang.lightnat.common.message.transfer.DisconnectPush;
import com.xuzhiguang.lightnat.server.core.server.transfer.TransferChannelManager;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ConnectRequestProcessor implements MessageProcessor {
    @Override
    public void process(ChannelHandlerContext ctx, NatMessage natMessage) {

        log.debug("transfer ConnectRequestProcessor. channel:{}", ctx.channel());

        if (natMessage.getBody() instanceof ConnectRequest) {
            ConnectRequest request = (ConnectRequest) natMessage.getBody();
            Channel proxyChannel = ProxyChannelManager.get(request.getSessionId());
            if (proxyChannel != null) {

                // 绑定 transferId 和 sessionId
                TransferChannelManager.setSessionId(ctx.channel(), request.getSessionId());
                Long transferId = TransferChannelManager.getTransferId(ctx.channel());
                ProxyChannelManager.setTransferId(proxyChannel, transferId);

                // 连接流程走完. 监听 op_read 事件
                proxyChannel.config().setAutoRead(true);

                log.info("transfer connected. sessionId:{}, transferId:{}", request.getSessionId(), transferId);

            } else {
                log.warn("proxyChannel is null. sessionId:{}", request.getSessionId());

                ctx.channel().writeAndFlush(new NatMessage(new DisconnectPush()));
            }
        }
    }
}
